package com.example.translateappjava.Service;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.util.Log;
import android.widget.Toast;

import androidx.annotation.NonNull;

import com.example.translateappjava.Activity.HomeFragmentActivity.GoodResultActivity;
import com.example.translateappjava.Activity.HomeFragmentActivity.BadResultActivity;
import com.example.translateappjava.Activity.HomeFragmentActivity.ResultActivity;
// 引入新的 Helper
import com.example.translateappjava.DataBase.UserInfo;
import com.example.translateappjava.Service.ChatGPT.ChatGptContextHelper;
// 保留旧的 Helper，以备其他地方可能还在使用（虽然DiabetesFoodAdvisor现在不用了）
// import com.example.translateappjava.Service.ChatGPT.ChatGptHelper;
import com.example.translateappjava.Singleton.GlobalData;
import com.example.translateappjava.Utils.ImageData;
import com.example.translateappjava.Utils.ImageDataLite;
import com.example.translateappjava.Listener.LoadingProgressListener;

// 不需要再从这里 import org.json.*, 因为解析逻辑封装在 ChatGptContextHelper.parseGptContentFromJson
// 或者如果 DiabetesFoodAdvisor 仍然需要直接解析，则保留

import org.json.JSONException;
import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;

public class DiabetesFoodAdvisor {

    private final Activity activity;
    private final ChatGptContextHelper chatGptContextHelper; // <<< 使用新的 Helper
    private String rr_single; // 用于单项处理时的识别结果 (重命名以区分)
    private Bitmap bm_single = null; // 用于单项处理时的位图 (重命名以区分)

    private int gptResponsesReceived = 0; // 重命名 iteratorTimes
    private int totalValidItemsForGptProcessing = 0; // 重命名 totalValidItemsForGpt

    private ArrayList<ImageData> currentImageDataList = null; // 列表处理时内部引用

    private LoadingProgressListener loadingProgressListener;

    public void setLoadingProgressListener(LoadingProgressListener listener) {
        this.loadingProgressListener = listener;
    }

    public void setBitmapForSingleItem(Bitmap bitmap) {
        this.bm_single = bitmap;
    }

    public DiabetesFoodAdvisor(Activity activity) {
        this.activity = activity;
        this.chatGptContextHelper = new ChatGptContextHelper(activity); // <<< 初始化新的 Helper
        this.chatGptContextHelper.setOnChatGptResponseListener(new ChatGptContextHelper.OnChatGptResponseListener() {
            @Override
            public void onChatGptResponse(String rawJsonResponse, Object context) {
                handleChatGptResponseInternal(rawJsonResponse, context);
            }

            @Override
            public void onError(String message, Object context) {
                handleErrorInternal(message, context);
            }
        });
    }

    // 单项处理 - 无Bitmap (依然通过rr_single和bm_single状态来区分，context会是null)
    public void processFoodRecognitionResult(String foodRecognitionResult) {
        this.rr_single = foodRecognitionResult;
        this.bm_single = null;
        this.currentImageDataList = null; // 清理列表状态
        String formattedQuestion = formatQuestionForGpt(foodRecognitionResult);
        Log.d("DiabetesFoodAdvisor", "单项请求(无图) for: " + foodRecognitionResult);
        // 对于单项请求，我们传递一个特殊的上下文或null。这里用null。
        chatGptContextHelper.chatGPTRequest(formattedQuestion, null);
    }

    // 单项处理 - 有Bitmap
    public void processFoodRecognitionResult(String foodRecognitionResult, Bitmap bitmap) {
        this.rr_single = foodRecognitionResult;
        setBitmapForSingleItem(bitmap);
        this.currentImageDataList = null; // 清理列表状态
        String formattedQuestion = formatQuestionForGpt(foodRecognitionResult);
        Log.d("DiabetesFoodAdvisor", "单项请求(有图) for: " + foodRecognitionResult);
        chatGptContextHelper.chatGPTRequest(formattedQuestion, null);
    }

    // 列表处理方法
    public void processFoodRecognitionResult(ArrayList<ImageData> receivedImageDataList) {
        this.currentImageDataList = receivedImageDataList;
        this.gptResponsesReceived = 0;
        this.totalValidItemsForGptProcessing = 0;
        this.rr_single = null; // 清理单项处理的状态
        this.bm_single = null;

        if (this.currentImageDataList != null) {
            for (ImageData data : this.currentImageDataList) {
                if (isValidRecognitionResultForGpt(data.getRecognitionResult())) {
                    this.totalValidItemsForGptProcessing++;
                }
            }
        }

        if (this.totalValidItemsForGptProcessing == 0) {
            Log.w("DiabetesFoodAdvisor", "列表处理：没有有效的识别结果可供GPT分析。");
            finalizeProcessing(this.currentImageDataList);
            return;
        }

        Log.d("DiabetesFoodAdvisor", "准备为 " + totalValidItemsForGptProcessing + " 个有效食物项进行GPT分析（列表）。");
        if (loadingProgressListener != null) {
            loadingProgressListener.onProgressUpdate("开始食物营养分析...", "共 " + totalValidItemsForGptProcessing + " 项");
        }

        int requestIndex = 0;
        for (ImageData currentData : this.currentImageDataList) {
            if (isValidRecognitionResultForGpt(currentData.getRecognitionResult())) {
                String formattedQuestion = formatQuestionForGpt(currentData.getRecognitionResult());
                Log.d("DiabetesFoodAdvisor", "列表项GPT请求 (" + (requestIndex + 1) + "/" + totalValidItemsForGptProcessing + "): " + currentData.getRecognitionResult());
                chatGptContextHelper.chatGPTRequest(formattedQuestion, currentData); // 传递ImageData作为context
                requestIndex++;
            }
        }
    }

    private boolean isValidRecognitionResultForGpt(String result) {
        return result != null &&
                !result.equals("待识别") &&
                !"null".equalsIgnoreCase(result) &&
                !"没调用到".equals(result) &&
                !result.contains("无食物") &&
                !result.contains("没有食物") &&
                !result.contains("非食物") &&
                !result.contains("识别失败");
    }

    private String formatQuestionForGpt(String recognitionResult) {
        GlobalData globalData = GlobalData.getInstance();
        String value = globalData.getGlobalVariable();
        return "食物：" + recognitionResult + "," + value + "能否食用？如果能请回复[1]，给出建议摄入量。如果不能回复[0]，请给出相应的科学依据，字数200左右。此外保持静默模式，不要输出回车换行，示例输出：[1] 建议摄入量：每日不超过m克。不宜xxx，适宜xxx";
    }

    private void handleChatGptResponseInternal(String rawJsonResponse, Object context) {
        // 使用 ChatGptContextHelper 提供的静态方法解析 content
        String actualContent = ChatGptContextHelper.parseGptContentFromJson(rawJsonResponse);

        if (context == null && rr_single != null) { // 单项处理 (context为null，且rr_single被设置)
            Log.d("DiabetesFoodAdvisor", "处理单项GPT响应 for '" + rr_single + "'");
            if (actualContent == null) {
                Toast.makeText(activity, "AI回复格式错误 (无法解析内容)", Toast.LENGTH_SHORT).show();
                // 也可以启动一个默认的错误结果页
            } else {
                if (actualContent.startsWith("[0]")) {
                    String scientificBasis = actualContent.length() > 3 ? actualContent.substring(3).trim() : "未提供具体依据";
                    if (bm_single == null) launchBadResultActivity(scientificBasis, rr_single);
                    else launchBadResultActivity(scientificBasis, rr_single, bm_single);
                } else if (actualContent.startsWith("[1]")) {
                    String intakeSuggestion = actualContent.length() > 3 ? actualContent.substring(3).trim() : "未提供具体建议";
                    if (bm_single == null) launchGoodResultActivity(intakeSuggestion, rr_single);
                    else launchGoodResultActivity(intakeSuggestion, rr_single, bm_single);
                } else {
                    Log.w("DiabetesFoodAdvisor", "单项处理：AI回复格式无法识别: " + actualContent.substring(0, Math.min(actualContent.length(),30)));
                    Toast.makeText(activity, "AI回复格式无法识别", Toast.LENGTH_SHORT).show();
                }
            }
            rr_single = null; // 清理单项状态
            bm_single = null;

        } else if (context instanceof ImageData) { // 列表项处理
            ImageData itemBeingProcessed = (ImageData) context;
            Log.d("DiabetesFoodAdvisor", "处理列表项GPT响应 for '" + itemBeingProcessed.getRecognitionResult() + "'");

            if (actualContent == null) {
                itemBeingProcessed.setSuggestion("AI回复格式错误(无法解析)");
                itemBeingProcessed.setEatable(false);
            } else {
                itemBeingProcessed.setEatable(actualContent.startsWith("[1]"));
                if (actualContent.length() > 3) {
                    itemBeingProcessed.setSuggestion(actualContent.substring(3).trim());
                } else {
                    itemBeingProcessed.setSuggestion(itemBeingProcessed.isEatable() ? "建议适量食用" : "不建议食用，具体原因未知");
                }
                Log.d("DiabetesFoodAdvisor", "ImageData更新后: " + itemBeingProcessed.toString());
                Log.d("UserID调试", "userName: " + UserInfo.getsUserInfo().getUsername());
                Log.d("history调试","foodName："+itemBeingProcessed.getRecognitionResult());
                Log.d("history调试","imgURL："+itemBeingProcessed.getImageURL());
                Log.d("history调试","result："+itemBeingProcessed.getSuggestion());
                // 准备发送给后端的数据
                String userName = UserInfo.getsUserInfo().getUsername();
                String foodName = itemBeingProcessed.getRecognitionResult();
                String imgURL = itemBeingProcessed.getImageURL();
                String resultSuggestion = itemBeingProcessed.getSuggestion(); // 根据你的log，"result"对应的是suggestion

                // 1. 创建 OkHttpClient 实例
                OkHttpClient client = new OkHttpClient();

                // 2. 构建请求体 (x-www-form-urlencoded)
                RequestBody formBody = new FormBody.Builder()
                        .add("userName", userName)
                        .add("foodName", foodName)
                        .add("imgUrl", imgURL)        // 后端参数是 imgUrl
                        .add("result", resultSuggestion) // 后端参数是 result
                        .build();

                // 3. 构建请求地址
                String url = GlobalData.getInstance().getBaseUrl() + "/search/liu/addHistory";
                Log.d("HistoryAPI_Request", "POST URL: " + url); // 日志记录请求URL

                // 4. 创建 POST 请求
                Request request = new Request.Builder()
                        .url(url)
                        .post(formBody)
                        .build();

                // 5. 发送异步请求
                client.newCall(request).enqueue(new Callback() {
                    @Override
                    public void onFailure(@NonNull Call call, @NonNull IOException e) {
                        // 请求失败回调
                        Log.e("HistoryAPI_Response", "Add history POST request failed: " + e.getMessage(), e);
                    }

                    @Override
                    public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                        // 请求成功回调
                        try (ResponseBody responseBody = response.body()) { // 使用 try-with-resources确保 responseBody 被关闭
                            if (!response.isSuccessful()) {
                                // HTTP 状态码不是 2xx
                                Log.e("HistoryAPI_Response", "Add history POST request unsuccessful. HTTP code: " + response.code());
                                if (responseBody != null) {
                                    Log.e("HistoryAPI_Response", "Error Response: " + responseBody.string());
                                }
                                return;
                            }

                            // HTTP 状态码是 2xx
                            if (responseBody == null) {
                                Log.w("HistoryAPI_Response", "Add history POST response successful, but response body is null.");
                                return;
                            }

                            String responseData = responseBody.string(); // 读取响应体内容
                            Log.d("HistoryAPI_Response", "Raw server response: " + responseData);

                            try {
                                // 解析后端返回的 JSON
                                JSONObject jsonResponse = new JSONObject(responseData);
                                int code = jsonResponse.optInt("code", -1); // 使用 optInt 提供默认值以防字段不存在
                                String msg = jsonResponse.optString("msg", "Unknown server message");

                                if (code == 200) {
                                    Log.i("HistoryAPI_Response", "History added successfully to backend. Server message: " + msg);
                                } else {
                                    Log.w("HistoryAPI_Response", "Backend reported an error for history add. Code: " + code + ", Message: " + msg);
                                }
                            } catch (JSONException e) {
                                Log.e("HistoryAPI_Response", "Failed to parse JSON response from backend: " + e.getMessage());
                                Log.d("HistoryAPI_Response", "Problematic JSON string for parsing: " + responseData);
                            }
                        }
                    }
                });
            }

            gptResponsesReceived++;
            updateProgressAndCheckCompletion();

        } else {
            Log.w("DiabetesFoodAdvisor", "收到GPT响应，但上下文未知或状态不匹配。Context: " + context + ", rr_single: " + rr_single);
            Toast.makeText(activity, "AI回复处理异常", Toast.LENGTH_SHORT).show();
            // 如果是列表处理中途发生的未知上下文，也尝试递增计数器
            if (this.currentImageDataList != null && this.totalValidItemsForGptProcessing > 0) {
                gptResponsesReceived++;
                updateProgressAndCheckCompletion();
            }
        }
    }

    private void handleErrorInternal(String errorMessage, Object context) {
        Log.e("DiabetesFoodAdvisor", "GPT请求出错: " + errorMessage + ". Context: " + (context != null ? context.getClass().getSimpleName() : "null"));

        if (context == null && rr_single != null) { // 单项处理错误
            Toast.makeText(activity, "AI分析食物 '" + rr_single + "' 时出错: " + errorMessage, Toast.LENGTH_LONG).show();
            rr_single = null;
            bm_single = null;
        } else if (context instanceof ImageData) { // 列表项处理错误
            ImageData itemWithError = (ImageData) context;
            itemWithError.setSuggestion("AI分析失败: " + errorMessage);
            itemWithError.setEatable(false);
            Log.w("DiabetesFoodAdvisor", "GPT handleError for ImageData: " + itemWithError.getRecognitionResult());

            gptResponsesReceived++;
            updateProgressAndCheckCompletion();
        } else { // 未知上下文的错误
            Toast.makeText(activity, "AI分析时发生未知错误: " + errorMessage, Toast.LENGTH_LONG).show();
            if (this.currentImageDataList != null && this.totalValidItemsForGptProcessing > 0) {
                gptResponsesReceived++;
                updateProgressAndCheckCompletion();
            }
        }
    }

    private void updateProgressAndCheckCompletion() {
        if (loadingProgressListener != null && totalValidItemsForGptProcessing > 0) { // 仅在列表处理时更新进度
            if (gptResponsesReceived < totalValidItemsForGptProcessing) {
                loadingProgressListener.onProgressUpdate(
                        "已分析 " + gptResponsesReceived + " 项食物...",
                        "共 " + totalValidItemsForGptProcessing + " 项待分析"
                );
            } else {
                loadingProgressListener.onProgressUpdate("所有食物分析完成，即将展示结果...");
            }
        }

        if (gptResponsesReceived == totalValidItemsForGptProcessing && totalValidItemsForGptProcessing > 0) {
            Log.d("DiabetesFoodAdvisor", "所有 " + totalValidItemsForGptProcessing + " 个有效列表项的GPT响应/错误已处理。");
            finalizeProcessing(this.currentImageDataList);
        }
    }

    private void finalizeProcessing(ArrayList<ImageData> listToDisplay) {
        if (loadingProgressListener != null) {
            // 使用Handler确保UI操作在主线程，并给予一点延迟让用户看到“完成”消息
            new android.os.Handler(android.os.Looper.getMainLooper()).postDelayed(() -> {
                if (loadingProgressListener != null) loadingProgressListener.onProcessingComplete();
                launchMultiResultActivity(listToDisplay);
            }, (listToDisplay != null && !listToDisplay.isEmpty() && totalValidItemsForGptProcessing > 0) ? 1000 : 100); // 如果有处理项，延迟长一点
        } else {
            launchMultiResultActivity(listToDisplay);
        }
    }


    private void launchMultiResultActivity(ArrayList<ImageData> finalList) {
        // (这个方法与之前的版本基本相同，确保它使用 finalList)
        ArrayList<ImageDataLite> imageDataLiteList = new ArrayList<>();
        if (finalList != null) {
            for (ImageData data : finalList) {
                String recognitionResult = data.getRecognitionResult();
                // 确保 suggestion 字段在传递给 ImageDataLite 前有值
                if (data.getSuggestion() == null || data.getSuggestion().equals("EMPTY") || data.getSuggestion().equals("待AI分析")) {
                    // 如果是有效识别结果但GPT未处理或处理失败，给一个默认提示
                    if(isValidRecognitionResultForGpt(recognitionResult) && (data.getSuggestion() == null || data.getSuggestion().equals("待AI分析"))){
                        data.setSuggestion("AI分析待完成或失败"); // 或者更具体的错误提示
                    } else if (!isValidRecognitionResultForGpt(recognitionResult)) {
                        data.setSuggestion("无需AI分析");
                    }
                }

                if (recognitionResult != null && !"null".equalsIgnoreCase(recognitionResult) && !"没调用到".equals(recognitionResult)) {
                    imageDataLiteList.add(new ImageDataLite(data));
                } else {
                    Log.d("DiabetesFoodAdvisor", "跳过无效识别结果的条目传递到ResultActivity: " + recognitionResult);
                }
            }
        }

        Log.d("DiabetesFoodAdvisor", "准备启动ResultActivity，共 " + imageDataLiteList.size() + " 个条目。");
        for (ImageDataLite itemLite : imageDataLiteList) {
            Log.d("DiabetesFoodAdvisor", "ImageDataLite: " + itemLite.toString());
        }

        Intent intent = new Intent(activity, ResultActivity.class);
        intent.putParcelableArrayListExtra("imageDataLiteList", imageDataLiteList);
        activity.startActivity(intent);
        // 清理列表引用，避免内存泄漏或下次调用时数据混淆
        this.currentImageDataList = null;
        this.totalValidItemsForGptProcessing = 0;
        this.gptResponsesReceived = 0;
    }

    // --- launchGood/BadResultActivity 和 bitmapToByteArray 方法保持不变 ---
    private void launchGoodResultActivity(String intakeSuggestion, String recognitionResult) {
        Intent intent = new Intent(activity, GoodResultActivity.class);
        intent.putExtra("intakeSuggestion", intakeSuggestion);
        intent.putExtra("recognitionResult", recognitionResult);
        activity.startActivity(intent);
    }

    private void launchGoodResultActivity(String intakeSuggestion, String recognitionResult, Bitmap bitmap) {
        Intent intent = new Intent(activity, GoodResultActivity.class);
        intent.putExtra("intakeSuggestion", intakeSuggestion);
        intent.putExtra("recognitionResult", recognitionResult);
        intent.putExtra("bitmap", bitmapToByteArray(bitmap));
        activity.startActivity(intent);
    }

    private void launchBadResultActivity(String scientificBasis, String recognitionResult) {
        Intent intent = new Intent(activity, BadResultActivity.class);
        intent.putExtra("scientificBasis", scientificBasis);
        intent.putExtra("recognitionResult", recognitionResult);
        activity.startActivity(intent);
    }

    private void launchBadResultActivity(String scientificBasis, String recognitionResult, Bitmap bitmap) {
        Intent intent = new Intent(activity, BadResultActivity.class);
        intent.putExtra("scientificBasis", scientificBasis);
        intent.putExtra("recognitionResult", recognitionResult);
        intent.putExtra("bitmap", bitmapToByteArray(bitmap));
        activity.startActivity(intent);
    }

    private byte[] bitmapToByteArray(Bitmap bitmap) {
        if (bitmap == null) return null;
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 45, stream);
        return stream.toByteArray();
    }
}